package UIFree.controls
{
	import UIFree.uif_component;
	import UIFree.uif_ecomponent;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	public class uif_pagination extends uif_ecomponent {
		private var _page: int = -1;
		private var _pages: int = 0;
		private var _layer: uif_ecomponent;
		public function uif_pagination(parent:uif_component, ax:int=0, ay:int=0, awidth:int=0, aheight:int=0, styleClass:Object='') {
			super(parent, ax, ay, awidth, aheight, styleClass);
		}
		
		public function get pages(): int {
			return _pages;
		}
		
		public function set pages(a_value: int): void {
			if (pages != a_value) setPages(a_value);
		}
		
		public function get page(): int {
			return _page;
		}
		
		public function set page(a_value: int): void {
			if (_page != a_value) setPage(a_value);
		}
		
		protected function setPages(a_value: int): void {
			_pages = a_value;
			_layer.disposeChilds();
			var irect: Rectangle = _layer.getInner();
			irect.width /= _pages;
			for (var i: int=0; i<a_value; i++) {
				createItem(i, irect);
				irect.x += irect.width;
			}
		}
		
		protected function setPage(a_value: int): void {
			_page = a_value;
			if (_page > -1) {
				_layer.forEach(function(item: uif_hotspotButton): void {
					if (item._data == _page) item.checked = true;
				});
			}
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		protected function createItem(index: int, irect: Rectangle): uif_hotspotButton {
			var item: uif_hotspotButton =  new uif_hotspotButton(_layer, irect.x, irect.y, irect.width, irect.height, style.item);
			item.addEvent(Event.CHANGE, doPageChange);
			item._data = index;
			item.group = 'paginator';
			return item;
		}
		
		private function doPageChange(e: Event): void {
			if (e.currentTarget.checked) page = e.currentTarget._data as int;
		}
		
		override protected function updateBounds():uif_component {
			super.updateBounds();
			var rect: Rectangle = getInner();
			if (!_layer) _layer = new uif_ecomponent(this, rect.x, rect.y, rect.width, rect.height, style.layer);
			else _layer.resize(rect.width, rect.height);
			return this;
		}
	}
}